package com.example.lib_common_ui.base

import android.os.Bundle
import android.view.LayoutInflater
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

abstract class BaseActivity<T : ViewBinding> : AppCompatActivity() {

    // 使用可空类型避免内存泄漏
    private var _binding: T? = null
    protected val binding: T get() = _binding ?: throw IllegalStateException("Binding is null")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        // 初始化绑定
        _binding = initBinding()
        setContentView(binding.root)

        // 使用绑定根视图处理系统栏
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initUI()
    }

    protected open fun initUI() {
        // 子类可覆盖此方法进行UI初始化
    }

    @Suppress("UNCHECKED_CAST")
    private fun initBinding(): T {
        // 获取泛型类型
        val type = (javaClass.genericSuperclass as? ParameterizedType)
            ?: throw IllegalStateException("Missing generic type parameter")

        // 获取绑定类
        val clazz = type.actualTypeArguments[0] as Class<*>

        // 查找inflate方法
        val method = clazz.getDeclaredMethod("inflate", LayoutInflater::class.java)
        return method.invoke(null, layoutInflater) as T
    }

    override fun onDestroy() {
        super.onDestroy()
        // 清理绑定引用，避免内存泄漏
        _binding = null
    }
}